package org.micode.common.helper;

import lombok.extern.slf4j.Slf4j;
import org.micode.common.utils.StringExtUtils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * Ping助手工具
 */
@Slf4j
public class PingHelper {

    /**
     * 通过ping命令判断是否离线
     *
     * @return 本服务器是否离线（没有连接到Internet或者时间服务器的网络）
     */
    public static boolean ping(String pingHostName) {
        if (StringExtUtils.isAnyEmpty(pingHostName)) {
            pingHostName = "www.baidu.com";
        }

        Runtime run = Runtime.getRuntime();
        try {
            Process process = run.exec(getPingCmd(pingHostName));
            try {
                try (InputStream s = process.getInputStream()) {
                    try (BufferedReader bis = new BufferedReader(new InputStreamReader(s))) {
                        int connectedCount = 0;
                        String line = bis.readLine();
                        while (line != null) {
                            connectedCount += getCheckResult(line);
                            line = bis.readLine();
                        }
                        return connectedCount >= 2;
                    }
                }
            } finally {
                process.destroy();
            }
        } catch (IOException ex) {
            log.warn("IOException for offLine({})", pingHostName, ex);
        }
        return false;
    }

    private static int getCheckResult(String line) {
        String str = line.toLowerCase();
        return str.contains("ttl=") ? 1 : 0;
    }

    private static String getPingCmd(String pingHostName) {
        String os = System.getProperty("os.name");
        if (os.contains("Linux")) {
            return "ping -c 100 -i 0 " + pingHostName;
        } else {
            return "ping -n 5 -w 1000 " + pingHostName;
        }
    }

    public static void main(String[] args) {
        if (ping("")) {
            log.info("ok!!!!");
        } else {
            log.warn("fail!!!!");
        }
    }

}
